package other.edan.erp.k3;


import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.data.model.SnCode__c;
import com.rkhd.platform.sdk.data.model.SyncConfig__c;
import com.rkhd.platform.sdk.exception.AsyncTaskException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.edan.erp.apitool.EdanK3Utils;
import other.edan.erp.utils.HCXObjectService;
import other.edan.erp.utils.ResultBody;
import other.edan.erp.utils.ResultVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 同步K3销售出库SN码
 * @Author 黎炎松
 * 2024-11-14 16:23
 */
@RestApi(baseUrl = "/edan/snCode")
public class SyncSnCode extends SyncSuper implements ScheduleJob, FutureTask {
    private static XoqlService xoqlService = XoqlService.instance();
    private static final Logger LOGGER = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "同步K3销售出库SN码 ==> ";

    // 执行定时任务
    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        LOGGER.debug(LOGGER_MSG + " 执行定时任务开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
            LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            LOGGER.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    // 执行异步函数
    @Override
    public void execute(String s) throws ScriptBusinessException {
        startSyncSnCode();
    }

    /**
     * 手动触发同步
     * @param
     * @return
     */
    @RestMapping(value = "/handerSync", method = RequestMethod.POST)
    public ResultVo handerSync() throws AsyncTaskException {
        LOGGER.debug("手动触发同步");
        String messageId = FutureTaskService.instance().addFutureTask(getClass(), "");
        LOGGER.info(LOGGER_MSG + "异步ID:" + messageId);
        return ResultVo.success("开通同步");
    }


    public static void main(String[] args) {
        HCXObjectService.isLocal = true;
        new SyncSnCode().startSyncSnCode();
    }

    /**
     * 开始同步SN码
     */
    public ResultVo startSyncSnCode() {
        try {
            LOGGER.debug(LOGGER_MSG + "处理开始");

            // 从数据配置表中获取数据
            SyncConfig__c syncConfig = getSyncConfig("K3_XXCK_SN");

            // todo
            String startDate = syncConfig.getAttribute("startDate");
            String endDate = syncConfig.getAttribute("endDate");
            startDate = "2022-01-20 00:00:00";
            endDate = "2024-08-30 00:00:00";

            // 设置参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("page", "1");
            paramsMap.put("pageSize", "10");
            paramsMap.put("StartDate", startDate);
            paramsMap.put("EndDate", endDate);
            LOGGER.debug(LOGGER_MSG + " paramsMap: " + paramsMap);

            // 发送请求获取数据
            // todo (去除token)
            ResultBody response = EdanK3Utils.sendGet(paramsMap, EdanK3Utils.GET_SALES_OUT_SN, "");
            if (!Objects.equals(response.getCode(), "200")) {
                LOGGER.debug(LOGGER_MSG + "查询k3数据异常: " + response.getMessage());
                return ResultVo.error("查询k3数据异常: " + response.getMessage());
            }

            // 获取数据 判断是否有值
            JSONObject result = (JSONObject) response.getResult();
            List<JSONObject> k3DataList = JSONObject.parseArray(result.getJSONArray("ICSerialInfos").toJSONString(), JSONObject.class);
            LOGGER.debug(LOGGER_MSG + "查询返回的数据: " + k3DataList.size());
            if (k3DataList.size() <= 0) {
                LOGGER.debug(LOGGER_MSG + "暂无需要处理的数据");
                // 同步修改配置表
                upSyncConfig(syncConfig);
                return ResultVo.success();
            }

            // 获取系统中存在的数据
            Map<String, Long> crmCodeMap = getCrmDataMap("snCode", "fserialNum", k3DataList);

            // 获取系统中的销售出库明细 (明细标识：主表id + 明细序号)
            String filterVals = k3DataList.stream().map(v -> "'" + v.getString("finterID") + v.getString("fentryID") + "'").collect(Collectors.joining(","));
            String sql = String.format("select id,edanId__c from salesOutReceiptDetails__c where edanId__c in (%s)", filterVals);
            Map<String, Long> crmOutDetailMap = xoqlService.query(sql).getRecords().stream().collect(Collectors.toMap(e -> e.getString("edanId__c"), e1 -> e1.getLong("id")));
            LOGGER.debug(LOGGER_MSG + "crmOutDetailMap: " + crmOutDetailMap);


            // 获取新增、修改的数据
            List<SnCode__c> crmAddList = new ArrayList<>(); // CRM新增集合
            List<SnCode__c> crmUpList = new ArrayList<>(); // CRM修改集合
            for (JSONObject sn : k3DataList) {
                // 处理出库
                SnCode__c snCode = new SnCode__c();
                String edanId = sn.getString("finterID") + sn.getString("fentryID");
                String code = sn.getString("fserialNum");

                snCode.setEntityType(3533379737983570L);
                snCode.setEdanId__c(edanId); // 数据id
                snCode.setSnCode__c(code); // SN 码
                snCode.setSalesOutReceiptDetails__c(crmOutDetailMap.get(edanId)); // 销售出库明细
                snCode.setRemark__c(sn.getString("remark")); // 备注

                // 判断系统中是否存在，存在则更新
                LOGGER.debug(LOGGER_MSG + "snCode = " + snCode);
                if (crmCodeMap.containsKey(code)) {
                    snCode.setId(crmCodeMap.get(code));
                    crmUpList.add(snCode);
                } else {
                    crmAddList.add(snCode);
                }

                // 进行新增、更新
                if (crmAddList.size() >= 100) {
                    HCXObjectService.updateBatch(crmAddList);
                    crmAddList.clear();
                }
                if (crmUpList.size() >= 100) {
                    HCXObjectService.updateBatch(crmUpList);
                    crmUpList.clear();
                }
            }


            // 进行批量新增、更新
            HCXObjectService.insertBatch(crmAddList);
            HCXObjectService.updateBatch(crmUpList);

            // 更新同步配置
            upSyncConfig(syncConfig);

            LOGGER.debug(LOGGER_MSG + "处理成功");
            return ResultVo.success();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.debug(LOGGER_MSG + "处理异常:" + e.getMessage());
            return ResultVo.error("处理异常: " + e.getMessage());
        }
    }



}
